package com.taxis.service;

import java.util.List;
import org.hibernate.*;

import com.taxis.common.*;
import com.taxis.model.Peticion;
import com.taxis.model.Usuario;

public class PeticionDaoService {

	private List<Peticion> peticiones;
	private Peticion peticion;

	public PeticionDaoService(){ }

	public void insertPeticion(Peticion p) throws Exception{
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try{
			tx = session.beginTransaction();
			session.save(p);
			tx.commit();
		}catch(RuntimeException re){
			if(p != null){
				tx.rollback();
			}
			throw re;
		}finally{
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Peticion> getAllPeticiones() {
		Session session = HibernateUtil.currentSession();
		try {
			Query q = session.getNamedQuery("getAllPeticiones");
			peticiones = (List<Peticion>)q.list();
			return peticiones;
		} catch(Exception e) {
			System.out.println("Error while fetching PETICIONES");
			e.printStackTrace();
			return null;
		} finally {
			session.close();        	
		}
	}

	public List getPeticionesUsuario(int usuario){
		Session session = HibernateUtil.currentSession();
		
		try{
			session.beginTransaction();
			return session.createQuery("from Peticion p WHERE p.usuario = :usuario").setInteger("usuario", usuario).list();
		}
		catch(Exception e){
			System.out.print("Error while fetching" + e);
			return null;
		}
		finally{
			session.close();
		}
	}
	
	public List getPeticionesAdmin(){
		Session session = HibernateUtil.currentSession();
		
		try{
			session.beginTransaction();
			return session.createQuery("from Peticion p WHERE p.estado = :atendida").setString("atendida", "NoAtendida").list();
		}
		catch(Exception e){
			System.out.print("Error while fetching" + e);
			return null;
		}
		finally{
			session.close();
		}
	}
	
	public Peticion getPeticion(Integer idPeticion) throws Exception {
		Session session = HibernateUtil.currentSession();
		try {
			System.out.println("entrando a try con "+ idPeticion);
			return (Peticion)session.get(Peticion.class, idPeticion);
		} finally {
			session.close();
		}
	}

	public void updatePeticion(Peticion p) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.update(p);
			tx.commit();
		} catch(RuntimeException re) {
			if(p != null)
				tx.rollback();
			throw re;
		} finally {
			session.close();
		}
	}

	public void deletePeticion(Integer idPeticion) throws Exception {
		Session session = HibernateUtil.currentSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			peticion = (Peticion)session.load(Peticion.class, idPeticion);
			session.delete(peticion);
			tx.commit();
		} catch (RuntimeException e) {
			if(peticion != null)
				tx.rollback();
			throw e;
		} finally {
			session.close();
		}
	}
}